package algorithm.leetcode.simple;

/*
 给定一个链表，判断链表中是否有环。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/15
 */
public class Question141 {
    public static void main(String[] args) {

    }

    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        // 慢节点
        ListNode slow = head;
        // 快节点
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}
